﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MaxZhang.EasyEntities.Persistence;
using MaxZhang.EasyEntities.Persistence.Provider;
namespace ExORMDesginer.Services
{
    /// <summary>
    /// SQL Server 写表列扩展属性接口(支持2005以上)
    /// </summary>
    public class SqlDatabaseDescriptionWriter : IDatabaseDescriptionWriter
    {

        public bool Write()
        {
            using (var session = new DbSession(new SqlProvider(ConnectionString)))
            {
                if (!string.IsNullOrEmpty(TableDescription))
                {
                    string execTableDescSQL = string.Format(tableDescriptionSQL,TableName,TableDescription);
                    session.Execute(new Command(execTableDescSQL));
                }

                if (ColumnsDescription != null && ColumnsDescription.Count > 0)
                {

                    foreach (var cd in ColumnsDescription)
                    {
                        string execColumnDescSQL = string.Format(columnDescriptionSQL, TableName,cd.Name,cd.Description);
                        session.Execute(new Command(execColumnDescSQL));
                    }
                }

            }

            return true;
        }

        private string tableDescriptionSQL =
            @"if exists (SELECT 1 FROM fn_listextendedproperty (NULL, 'schema', 'dbo', 'table', N'{0}', NULL, NULL)) 
                 EXECUTE sp_updateextendedproperty  N'MS_Description', N'{1}',N'user', N'dbo',N'table',N'{0}',NULL,NULL  
               else 
	             EXECUTE sp_addextendedproperty N'MS_Description', N'{1}',N'user', N'dbo',N'table', N'{0}', NULL,NULL";


        private string columnDescriptionSQL =
            @"if exists (select 1 from fn_listextendedproperty (NULL, 'user', 'dbo', 'table', '{0}', 'column', '{1}'))
	             EXECUTE sp_updateextendedproperty N'MS_Description', N'{2}',N'user', N'dbo',N'table', N'{0}', N'column',N'{1}' 
               else 
	             EXECUTE sp_addextendedproperty N'MS_Description', N'{2}',N'user', N'dbo',N'table', N'{0}', N'column',N'{1}' ";



        public string TableName { get; set; }

        public string TableDescription { get; set; }

        public string ConnectionString { set; get; }

        public List<ColumnsDescriptionInfo> ColumnsDescription { get; set; }
    }
}
